<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图层切换控件</title>
    <link rel="stylesheet" href="./css/ol.css"/>
    <script src="./js/ol.js"></script>
</head>

<body>
<div id="controls">
    <input type="checkbox" id="osm" checked/>OpenStreetMap
    <input type="checkbox" id="bingmap"/>Bing Map
    <input type="checkbox" id="stamen"/>Stamen Map
</div>
<div id="map"></div>

<script>
    let map = new ol.Map({
        target: 'map',                          // 关联到对应的div容器
        layers: [
            new ol.layer.Tile({                 // OpenStreetMap图层
                source: new ol.source.OSM()
            }),
            new ol.layer.Tile({                 // Bing Map图层
                source: new ol.source.BingMaps({
                    key: '略',    // 可以自行到Bing Map官网申请key
                    imagerySet: 'Aerial'
                }),
                visible: false                  // 先隐藏该图层
            }),
            new ol.layer.Tile({
                source: new ol.source.Stamen({
                    layer: 'watercolor'
                }),
                visible: false                  // 先隐藏该图层
            })
        ],
        view: new ol.View({                     // 地图视图
            projection: 'EPSG:3857',
            center: [0, 0],
            zoom: 0
        })
    });

    let controls = document.getElementById('controls');
    // 事件委托
    controls.addEventListener('click', (event) => {
        if (event.target.checked) {                       // 如果选中某一复选框
            // 通过DOM元素的id值来判断应该对哪个图层进行显示
            switch (event.target.id) {
                case "osm":
                    map.getLayers().item(0).setVisible(true);
                    break;
                case "bingmap":
                    map.getLayers().item(1).setVisible(true);
                    break;
                case "stamen":
                    map.getLayers().item(2).setVisible(true);
                    break;
                default:
                    break;
            }
        } else {                                         // 如果取消某一复选框
            // 通过DOM元素的id值来判断应该对哪个图层进行隐藏
            switch (event.target.id) {
                case "osm":
                    map.getLayers().item(0).setVisible(false);
                    break;
                case "bingmap":
                    map.getLayers().item(1).setVisible(false);
                case "stamen":
                    map.getLayers().item(2).setVisible(false);
                default:
                    break;
            }
        }
    });
</script>
</body>
</html>